package org.laizili.solution.leetcode;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/stickers-to-spell-word/">691. 贴纸拼词<a/>
 * <p>
 * tags: 动态规划; 递归+回溯（dfs）; 记忆化搜索; 状态压缩
 */
public class Problem691 {
    private static class Solution {
        public int minStickers(String[] stickers, String target) {
            int len = target.length();
            int[] memo = new int[1 << len];
            Arrays.fill(memo, -1);
            memo[0] = 0;
            int dp = dp(stickers, target, memo, (1 << len) - 1);
            return dp <= len ? dp : -1;

        }

        public int dp(String[] stickers, String target, int[] memo, int state) {
            if (memo[state] == -1) {
                int ans = target.length() + 1;
                for (String sticker : stickers) {
                    int curState = state;
                    int[] cnt = new int[26];
                    int len = sticker.length();
                    for (int i = 0; i < len; i++) {
                        cnt[sticker.charAt(i) - 'a']++;
                    }
                    int lenTarget = target.length();
                    for (int i = 0; i < lenTarget; i++) {
                        int hs = target.charAt(i) - 'a';
                        if (((curState >> i) & 1) != 0 && cnt[hs] > 0) {
                            // curState ^= 1 << i;
                            curState &= ~(1 << i);
                            cnt[hs]--;
                        }
                    }
                    if (curState < state) {
                        ans = Math.min(ans, dp(stickers, target, memo, curState) + 1);
                    }
                }
                memo[state] = ans;
            }
            return memo[state];
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution().minStickers(new String[]{"with", "example", "science"}, "thehat"));
    }
}
